package com.zhxq.ai.service.impl;

import java.util.List;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhxq.common.utils.DateUtils;
import com.zhxq.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.cassandra.CassandraVectorStore;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.zhxq.ai.mapper.KnowledgeBaseMapper;
import com.zhxq.ai.domain.KnowledgeBase;
import com.zhxq.ai.service.IKnowledgeBaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 知识库管理Service业务层处理
 * 
 * @author zxs
 * @date 2025-06-02
 */
@Service
@RequiredArgsConstructor
public class KnowledgeBaseServiceImpl extends ServiceImpl<KnowledgeBaseMapper, KnowledgeBase> implements IKnowledgeBaseService
{
    @Autowired
    private KnowledgeBaseMapper knowledgeBaseMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    private final CassandraVectorStore vectorStore;

    /**
     * 查询知识库管理
     * 
     * @param id 知识库管理主键
     * @return 知识库管理
     */
    @Override
    public KnowledgeBase selectKnowledgeBaseById(Long id)
    {
        return knowledgeBaseMapper.selectKnowledgeBaseById(id);
    }

    /**
     * 查询知识库管理列表
     * 
     * @param knowledgeBase 知识库管理
     * @return 知识库管理
     */
    @Override
    public List<KnowledgeBase> selectKnowledgeBaseList(KnowledgeBase knowledgeBase)
    {
        return knowledgeBaseMapper.selectKnowledgeBaseList(knowledgeBase);
    }

    /**
     * 新增知识库管理
     * 
     * @param knowledgeBase 知识库管理
     * @return 结果
     */
    @Override
    public int insertKnowledgeBase(KnowledgeBase knowledgeBase)
    {
        knowledgeBase.setCreateTime(DateUtils.getNowDate());
        knowledgeBase.setUpdateTime(DateUtils.getNowDate());
        knowledgeBase.setCreateBy(SecurityUtils.getUsername());
        knowledgeBase.setUpdateBy(SecurityUtils.getUsername());
        return knowledgeBaseMapper.insertKnowledgeBase(knowledgeBase);
    }

    /**
     * 修改知识库管理
     * 
     * @param knowledgeBase 知识库管理
     * @return 结果
     */
    @Override
    public int updateKnowledgeBase(KnowledgeBase knowledgeBase)
    {
        if (knowledgeBase.getStatus() == 1) {
            throw new RuntimeException("该文件已上传至向量库中,请先禁用再进行修改操作");
        }
        knowledgeBase.setUpdateTime(DateUtils.getNowDate());
        knowledgeBase.setUpdateBy(SecurityUtils.getUsername());
        return knowledgeBaseMapper.updateKnowledgeBase(knowledgeBase);
    }

    /**
     * 批量删除知识库管理
     * 
     * @param ids 需要删除的知识库管理主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgeBaseByIds(Long[] ids)
    {
        return knowledgeBaseMapper.deleteKnowledgeBaseByIds(ids);
    }

    /**
     * 删除知识库管理信息
     * 
     * @param id 知识库管理主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgeBaseById(Long id)
    {
        KnowledgeBase kno = getById(id);
        if(kno.getStatus() == 1) {
            throw new RuntimeException("该文件已上传至向量库中,请先禁用再进行删除操作");
        }
        return knowledgeBaseMapper.deleteKnowledgeBaseById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeVector(KnowledgeBase knowledgeBase) {
        Long status = knowledgeBase.getStatus();
        String fileUrl = knowledgeBase.getFileUrl().replaceFirst("/profile", "");
        Resource resource = new FileSystemResource(profile + fileUrl);
        String filename = resource.getFilename();

        FilterExpressionBuilder b = new FilterExpressionBuilder();
        Filter.Expression expression = b.eq("file_name", filename).build();
        SearchRequest searchRequest = SearchRequest.builder().filterExpression(expression).build();
        List<Document> docList = vectorStore.similaritySearch(searchRequest);

        boolean vectorOpSuccess = false;

        try {
            if (status == 1) {
                if (CollUtil.isNotEmpty(docList)) {
                    throw new RuntimeException("该文件已上传至向量库中");
                }

                PagePdfDocumentReader reader = new PagePdfDocumentReader(
                        resource,
                        PdfDocumentReaderConfig.builder()
                                .withPageExtractedTextFormatter(ExtractedTextFormatter.defaults())
                                .withPagesPerDocument(1)
                                .build()
                );

                List<Document> documents = reader.read();
                vectorStore.add(documents); // 向量库写入
                vectorOpSuccess = true;

            } else {
                if (CollUtil.isEmpty(docList)) {
                    throw new RuntimeException("该文件不存在于向量库中");
                }
                vectorStore.delete(expression); // 向量库删除
                vectorOpSuccess = true;
            }

            // 如果一切正常，提交数据库变更
            knowledgeBaseMapper.updateKnowledgeBase(knowledgeBase);

        } catch (Exception e) {
            // 手动补偿：如果向量库操作成功而后续失败，删除刚插入的数据
            if (vectorOpSuccess && status == 1) {
                vectorStore.delete(expression); // 删除已添加的文档
            }
            throw e; // 抛出异常触发 @Transactional 回滚
        }
    }

}
